import { Component } from '@angular/core';
import {App, IonicPage, NavController, NavParams} from 'ionic-angular';
import {CommProvider} from "../../providers/CommProvider";
import {HttpService} from "../../providers/HttpService";
import {InfoProvider} from "../../providers/InfoProvider";

/**
 * Generated class for the ModifyPhonePage page.
 *
 * See http://ionicframework.com/docs/components/#navigation for more info
 * on Ionic pages and navigation.
 */
@IonicPage()
@Component({
    selector: 'page-modify-phone',
    templateUrl: 'modify-phone.html',
})
export class ModifyPhonePage {

    modify: {old_phone: string, new_phone: string, code: string} = {
        old_phone: null,
        new_phone: null,
        code: null
    };

    constructor(public navCtrl: NavController, public navParams: NavParams,
                private appCtrl: App,
                private commProvider: CommProvider,
                private infoProvider: InfoProvider,
                private httpService: HttpService) {
    }

    ionViewDidLoad() {
        console.log('ionViewDidLoad ModifyPhonePage');
    }

    onSendCode() {
        this.httpService.instance()
            .setUrl('/user/sendSmsCode')
            .setBody({
                type: 'modifyPhone',
                phone: this.modify.new_phone
            })
            .postRequest()
            .then(res => {
                if (res.status == 0) {
                    this.commProvider.showToast('验证码已发送');
                }
            });
    }

    onPasswordReset() {
        this.httpService.instance()
            .setUrl('/user/userModifyPhone')
            .setBody(this.modify)
            .putRequest()
            .then(res => {
                if (res.status == 0) {
                    this.commProvider.showToast('手机号修改成功, 请重新登录。');

                    this.httpService.instance()
                        .setUrl('/user/userLogout')
                        .postRequest()
                        .then(res => {
                            console.log('userLogout:', res);
                        });

                    this.appCtrl.getRootNav().setRoot('LoginPage')
                        .then(res => {
                            if (res) {
                                this.infoProvider.clearStorage();
                            }
                        });
                }
            });
    }
}
